package com.blb.demo;

import java.util.ArrayList;
import java.util.List;

/**
 * 包子店
 */
public class BaoziStore {

    /**
     * 缓冲区阈值
     */
    private static final int MAX = 100;
    /**
     * 包子缓冲区
     */
    private List<Baozi> baozis = new ArrayList<>();

    /**
     * 创建包子，放缓冲区
     */
    public synchronized void makeBaozi(){
        int size = baozis.size();
        //判断是否到缓冲区上限
        if(size == MAX){
            System.out.println("包子铺满了，包子师傅休息下" + Thread.currentThread().getName());
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //通知消费者买包子
        this.notifyAll();
        //创建包子
        Baozi baozi = new Baozi(baozis.size() + 1);
        //存入缓冲区
        baozis.add(baozi);
        System.out.println(Thread.currentThread().getName() + "包子师傅做了" + baozi);
    }

    /**
     * 卖包子，从缓冲区取
     */
    public synchronized void sellBaozi(){
        //判断缓冲区是否空
        if(baozis.size() == 0){
            System.out.println("包子铺空了，消费者休息下" + Thread.currentThread().getName());
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //通知生产者做包子
        this.notifyAll();
        if(baozis.size() > 0) {
            //从缓冲区取包子，并删除
            Baozi baozi = baozis.remove(0);
            System.out.println(Thread.currentThread().getName() + "消费者吃了" + baozi);
        }
    }
}
